// src/stores/user.js
import { defineStore } from 'pinia';
import { ref ,computed } from 'vue';
import { authApi } from '@/api/auth';

export const useUserStore = defineStore('user', () => {
  // 状态
  const userInfo = ref(null);
  const token = ref(null);
  const permissions = ref([]);
  
  // Getter函数
  const isLoggedIn = computed(() => !!token.value);
  const isAdmin = computed(() => userInfo.value?.role === 'admin');
  const isTeacher = computed(() => userInfo.value?.role === 'teacher');
  const isStudent = computed(() => userInfo.value?.role === 'student');
  const currentRole = computed(() => userInfo.value?.role || 'guest');
  
  // 初始化用户信息
  const initUser = async () => {
    const storedToken = localStorage.getItem('token');
    if (storedToken) {
      token.value = storedToken;
      try {
        // 调用API获取当前用户信息
        const response = await authApi.getCurrentUser();
        if (response.data.code === '000000') {
          userInfo.value = response.data.data;
          console.log('✅ 用户信息初始化成功:', userInfo.value);
        } else {
          console.error('❌ 获取用户信息失败:', response.data.msg);
          clearUser();
        }
      } catch (error) {
        console.error('💥 初始化用户信息失败:', error);
        clearUser();
      }
    }
  };
  
  // 登录
  // src/stores/user.js - 确保login方法正确
const login = async (credentials) => {
  try {
    const response = await authApi.login(credentials);
    console.log('📨 登录API响应:', response.data);
    
    if (response.data.code === '000000') {
      token.value = response.data.data.token;
      userInfo.value = response.data.data.user;
      
      // 存储token到localStorage
      localStorage.setItem('token', token.value);
      
      console.log('✅ 登录成功:', userInfo.value);
      return true;
    } else {
      console.error('❌ 登录失败:', response.data.msg);
      return false;
    }
  } catch (error) {
    console.error('💥 登录失败:', error);
    return false;
  }
};
  
  // 注册
  const register = async (userData) => {
    try {
      const response = await authApi.register(userData);
      if (response.data.code === '000000') {
        console.log('✅ 注册成功');
        return true;
      } else {
        console.error('❌ 注册失败:', response.data.msg);
        return false;
      }
    } catch (error) {
      console.error('💥 注册失败:', error);
      return false;
    }
  };
  
  // 登出
  const logout = async () => {
    try {
      await authApi.logout();
    } catch (error) {
      console.error('💥 登出失败:', error);
    } finally {
      clearUser();
    }
  };
  
  // 清除用户信息
  const clearUser = () => {
    userInfo.value = null;
    token.value = null;
    permissions.value = [];
    localStorage.removeItem('token');
    console.log('🚪 用户信息已清除');
  };
  
  // 设置权限
  const setPermissions = (newPermissions) => {
    permissions.value = newPermissions;
  };
  
  // 刷新token
  const refreshToken = async () => {
    try {
      const response = await authApi.refreshToken();
      if (response.data.code === '000000') {
        token.value = response.data.data.token;
        localStorage.setItem('token', token.value);
        console.log('🔄 Token刷新成功');
        return true;
      } else {
        console.error('❌ Token刷新失败:', response.data.msg);
        return false;
      }
    } catch (error) {
      console.error('💥 Token刷新失败:', error);
      return false;
    }
  };
  
  return {
    // 状态
    userInfo,
    token,
    permissions,
    
    // Getter
    isLoggedIn,
    isAdmin,
    isTeacher,
    isStudent,
    currentRole,
    
    // 方法
    initUser,
    login,
    register,
    logout,
    clearUser,
    setPermissions,
    refreshToken
  };
});